import { createSlice } from '@reduxjs/toolkit'

const tabsSlice = createSlice({
  name: 'tab',
  initialState: {
    isCollapse: false,
    tabList: [
      {
        path: '/',
        name: 'home',
        label: '首页'
      }
    ],
    currentMenu: {}
  },
  reducers: {
    CollapseMenu: (state) => {
      state.isCollapse = !state.isCollapse
    },
    setMenuList: (state, { payload: value }) => {
      if (value.name !== 'home') {
        state.currentMenu = value
        const result = state.tabList.findIndex(
          (item) => item.name === value.name
        )
        if (result === -1) {
          state.tabList.push(value)
        }
      } else if (value.name === 'home' && state.tabList.length === 1) {
        state.currentMenu = {}
      }
    },
    closeTag: (state, { payload: value }) => {
      let i = state.tabList.findIndex((item) => item.name === value.name)
      if (i > -1) {
        state.tabList.splice(i, 1)
      }
    },
    // 设置当前选择的菜单
    setCurrentMenu: (state, { payload: value }) => {
      if (value.name === 'home') {
        state.currentMenu = {}
      } else {
        state.currentMenu = value
      }
    }
  }
})

export const { CollapseMenu, setMenuList, closeTag, setCurrentMenu } =
  tabsSlice.actions
export default tabsSlice.reducer
